/*
 * @Author: xiaosihan 
 * @Date: 2022-06-01 10:21:29 
 * @Last Modified by: xiaosihan
 */

//@ts-ignore
import mysql from "mysql";
import utils from "./util/utils";

/**
 * 数据库对象
 *
 * @class Database
 */
class Database {

    constructor() {

        this.init();
    }

    connection = mysql.createConnection({
        host: utils.isProd ? "localhost" : '47.108.147.37',
        database: utils.isProd ? 'tray.prod' : 'tray.test',
        user: utils.isProd ? 'tray.prod' : 'tray.test',
        password: utils.isProd ? 'S3j4TzZZKtZMMPew' : 'scCdk8zNKaSRPLJa'
    });

    // 数据初始化
    init() {
        this.connection.connect((err: any) => {
            if (err) {
                console.log(err);
            } else {
                console.log("mysql连接成功");
            }
        });
    }



    // 查询邮箱用户名是否存在
    async checkEmailExit(email: string) {
        const result = await new Promise((resolve, reject) => {
            this.connection.query(`SELECT * FROM user WHERE email='${email}'`, function (error: any, results: any, fields: any) {
                if (error || results.length === 0) {
                    resolve(false);
                }
                resolve(true);
            });
        });
        return result;
    }

    // 添加用户
    async addUser(email: string, password: number) {
        const result = await new Promise((resolve, reject) => {
            this.connection.query(`INSERT INTO user (email, password, vip) VALUES ('${email}', '${password}', '999')`, function (error: any, results: any, fields: any) {
                if (error || results.length === 0) {
                    return reject('添加用户失败！');
                }
                resolve(true);
            });
        });
        return result;
    }


    //   更新用户 token 通过用户名
    async updataToken(id: string, token: number) {
        await new Promise((resolve, reject) => {
            this.connection.query(`UPDATE user token='${token}' WHERE id='${id}'`, function (error: any, results: any, fields: any) {
                if (error) {
                    reject(error);
                }
                resolve(results[0]);
            });
        });

    }

}

const database = new Database();

export default database;

